package com.itheima.controller;

import com.itheima.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
@RestController
public class CookieSessionController {
    // 设置Cookie
    @GetMapping("/setCookie")
    public Result setCookie(HttpServletResponse response) {
        response.addCookie(new Cookie("username", "angelababy"));   // 设置Cookie
        return Result.success();    // 响应Cookie
    }

    // 获取Cookie
    @GetMapping("/getCookie")
    public Result getCookie(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("username")) {
                log.info("username: {}", cookie.getValue());   // 输出name为username的Cookie
                break;
            }
        }
        return Result.success();
    }

    // 设置Session
    @GetMapping("/setSession")
    public Result setSession(HttpSession session) {
        session.setAttribute("session_username", "angelababy");
        session.setAttribute("session_password", "520521");
        System.out.println(session);
        return Result.success();    // 响应Session
    }

    // 获取Session
    @GetMapping("/getSession")
    public Result getSession(HttpServletRequest request) {
        HttpSession session = request.getSession();
        Object username = session.getAttribute("session_username");
        Object password = session.getAttribute("session_password");
        log.info("username: {}, password: {}", username, password);
        System.out.println(session);
        return Result.success();
    }
}
